package piuk.merchant;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.mtgox.api.ApiKeys;
import com.mtgox.examples.utils.FileSystem;

public class TickerClient {

	/**
	 * @param args
	 */
	public final String BTCE_URL = "https://btc-e.com/api/2/btc_usd/ticker";
	public final String MTGOX_URL = "https://data.mtgox.com/api/0/data/ticker.php?Currency=USD";
//	private Map<String,HttpURLConnection> conMap = new HashMap<String,HttpURLConnection>();
	
    public  class TickerBean{
    	double lastPrice;

		public double getLastPrice() {
			return lastPrice;
		}

		public void setLastPrice(double lastPrice) {
			this.lastPrice = lastPrice;
		}
    }
    
    public double getBTCeLastPrice() throws Exception{
        String response = fetchURL(BTCE_URL);  
        if (response == null) 
            throw new Exception("Null Reponse"); 
 
        //JSONObject jsonObject = new JSONObject(response);  
        Map<String, Object> obj = (Map<String, Object>) JSONValue.parse(response); 
        JSONObject tickerJson = (JSONObject)obj.get("ticker"); 
       return (Double)tickerJson.get("last");
    }
    
    public double getMTGOXLastPrice() throws Exception{
        String response = fetchURL(MTGOX_URL);  
        if (response == null) 
            throw new Exception("Null Reponse"); 
 
        //JSONObject jsonObject = new JSONObject(response);  
        Map<String, Object> obj = (Map<String, Object>) JSONValue.parse(response); 
        JSONObject dataJson = (JSONObject)obj.get("ticker"); 
        //JSONObject lastJson = (JSONObject)obj.get("last"); 
       return (Double)dataJson.get("last");
    }
    
    private static String fetchURL(String URL) throws Exception { 
        URL url = new URL(URL); 
 
        HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
        connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        connection.addRequestProperty("Accept", "application/xml"); 
 
        connection.setConnectTimeout(10000); 
 
        connection.setInstanceFollowRedirects(false); 
 
        connection.connect(); 
 
        if (connection.getResponseCode() != 200) { 
           throw new Exception("Invalid HTTP Response code " + connection.getResponseCode()); 
        } 
 
        return IOUtils.toString(connection.getInputStream(), "UTF-8"); 
    } 
	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		initSSL(); 
		TickerClient  ticker = new TickerClient();	
		//System.out.println(ticker.getBTCeLastPrice());
		System.out.println(ticker.getMTGOXLastPrice());
	}

    public static void initSSL()
    {        
           
        // SSL Certificates  trustStore ----------------------------------------
        //Set the SSL certificate for mtgox - Read up on Java Trust store. 
        System.setProperty("javax.net.ssl.trustStore","res/ssl/mtgox.jks");
        System.setProperty("javax.net.ssl.trustStorePassword","h4rdc0r_"); //I encripted the jks file using this pwd
        //System.setProperty("javax.net.debug","ssl"); //Uncomment for debugging SSL errors  
        
    }
    
     //readApiKeysFromFile
     public static ApiKeys readApiKeys(String pathToJsonFile) {
        //see https://code.google.com/p/json-simple/wiki/DecodingExamples
        JSONParser parser=new JSONParser();
        ApiKeys apiKeys = null;
        String apiStr = FileSystem.readFromFile(pathToJsonFile);
        try {
            JSONObject obj2=(JSONObject)(parser.parse(apiStr));
            apiKeys= new ApiKeys((String)obj2.get("mtgox_secret_key"), (String)obj2.get("mtgox_api_key"));
        } catch (ParseException ex) {
            System.err.println(ex);
        }
        return apiKeys;    
    }
}
